package com.mxs.activemq.usemq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 消息生产者
 */
public class JmsProducer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    private static final int SENDNUM= 3;

    public static void main(String[] args){

        // 连接工厂
        ConnectionFactory connectionFactory;
        //连接
        Connection connection = null;
        //回话
        Session session;
        //消息的目的地
        Destination destination;
        //消息的生产者
        MessageProducer messageProducer;


        //实例化连接工程
        connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEURL);

        try{
            //通过连接工厂获取连接
            connection = connectionFactory.createConnection();
            //启动连接
            connection.start();
            //创建session
            //第一个参数标识是否启用事务  第二个参数表示是否自动确认
            session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

            //destination = session.createTopic("HelloWorld");
            destination = session.createQueue("HelloWorld_queue");
            messageProducer = session.createProducer(destination);

            for(int i=0;i<SENDNUM;i++){
                String msg = "发送消息"+i+" "+System.currentTimeMillis();
                TextMessage message = session.createTextMessage(msg);
                messageProducer.send(message);
            }




        }catch (Exception e){
           e.printStackTrace();
        }finally {
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
